package io.renren.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.misc.BASE64Encoder;

/**
 * @author: huan.xu
 * @create: 2023/12/17 10:43
 * @description: 工具类
 **/
public class CommonUtil {

  private CommonUtil() {
  }

  /**
   * 下载文件
   *
   * @param originalFileName ：下载文件的原始文件名
   * @param file ：下载的文件
   * @param response ：相应对象
   */
  public static void downloadFile(String originalFileName, File file, HttpServletResponse response,
      HttpServletRequest request) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    OutputStream fos = null;
    try {
      bis = new BufferedInputStream(new FileInputStream(file));
      fos = response.getOutputStream();
      bos = new BufferedOutputStream(fos);

      String encodedFileName = URLEncoder.encode(originalFileName, "UTF-8");
      response.setHeader("Content-Disposition", "attachment;filename=\"" + encodedFileName + "\"");
      response.setContentType("application/force-download;charset=UTF-8");
      response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

      int byteRead = 0;
      byte[] buffer = new byte[8192];
      while ((byteRead = bis.read(buffer, 0, 8192)) != -1) {
        bos.write(buffer, 0, byteRead);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        bos.flush();
        bis.close();
        fos.close();
        bos.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static void setFileDownloadHeader(HttpServletRequest request,
      HttpServletResponse response, String fileName) {
    try {
      String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
      response.setHeader("Content-Disposition", "attachment;filename=\"" + encodedFileName + "\"");
      response.setContentType("application/force-download;charset=UTF-8");
      response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}
